<template>
  <div>
    <div class="createTest testPaper">
      <el-card class="title" v-loading="isLoading">
        <el-row>
          <el-col :span="23"
            ><div class="grid-content">
              <el-input
                v-model="examData.examTitle"
                class="testName"
                placeholder="请输入内容"
              ></el-input></div
          ></el-col>
          <el-col :span="1">
            <el-button type="primary" @click="save()"
              >保存<i class="el-icon-plus"></i
            ></el-button>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-cascader
              v-model="path"
              :options="examOptions"
              @change="examCategorychange"
              :props="{ value: 'id', label: 'categoryName' }"
              placeholder="请选试卷分类"
            ></el-cascader
          ></el-col>
          <el-col :span="6"
            ><div class="grid-content">
              <el-tag>答题时间:</el-tag>
              <el-input-number
                v-model="examData.limitTime"
                controls-position="right"
                :step="10"
                size="mini"
                :min="1"
              />
              分钟
            </div></el-col
          >
        </el-row>
      </el-card>
      <el-dialog
        :visible.sync="editQuestionVisible"
        :close-on-click-modal="false"
        append-to-body
        :show-close="false"
        center
      >
        <span slot="footer" class="dialog-footer">
          <el-row
            v-for="(item, index) in examData.questions"
            :key="index"
            class="ql-snow"
          >
            <el-col :span="12" class="ql-snow">
              <el-tag>{{ "问题" + (index + 1) }}</el-tag>
            </el-col>
            <el-col :span="8">
              <el-cascader
                v-model="item.path"
                :options="questionOptions"
                @change="questionTypeOptionChange($event, index)"
                :props="{ value: 'id', label: 'typeName' }"
                placeholder="请选择问题分类"
              ></el-cascader
            ></el-col>
          </el-row>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="questionEditConfirm"
            >确 定</el-button
          >
          <el-button @click="editQuestionVisible = false">取 消</el-button>
        </span>
      </el-dialog>
      <el-dialog
        :visible.sync="myEditor.dialogVisible"
        :close-on-click-modal="false"
        append-to-body
        style="width: 100%; height: 100%"
        :show-close="false"
        center
      >
        <span slot="footer" class="dialog-footer">
          <quill-editor
            v-model="myEditor.content"
            ref="myQuillEditor"
            :options="editorOption"
          ></quill-editor>
          <el-button type="primary" @click="editorConfirm">确 定</el-button>
          <el-button @click="myEditor.dialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
      <el-row>
        <el-col :span="22">
          <el-tabs
            v-model="currQuestion"
            type="border-card"
            @tab-remove="removeQuestion"
          >
            <el-tab-pane
              v-for="(item, index) in examData.questions"
              :key="item.analysis"
              :label="getQuestionPrefix(index)"
              :name="item.analysis"
            >
              <div class="ql-snow">
                <div class="ql-editor">
                  <el-input
                    class="ql-font-Segoe-UI ql-size-18px"
                    style="height: 200px"
                    v-html="item.questionTopic"
                    @click.native="inputClick(index, item.questionTopic, 1)"
                  ></el-input>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="1">
          <div style="margin-bottom: 20px">
            <el-button
              size="small"
              icon="el-icon-edit"
              title="编辑问题信息"
              circle
              @click="editQuestionVisible = true"
            ></el-button>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22">
          <el-tabs
            v-model="currQuestion"
            type="border-card"
            @tab-remove="removeQuestion"
          >
            <el-tab-pane
              v-for="(item, index) in examData.questions"
              :key="item.analysis"
              :label="getAnswerPrefix(index)"
              :name="item.analysis"
            >
              <div class="ql-snow">
                <div class="ql-editor">
                  <el-input
                    class="ql-font-Segoe-UI ql-size-18px"
                    style="height: 200px"
                    v-html="item.answer"
                    @click.native="inputClick(index, item.answer, 0)"
                  ></el-input>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import "@/assets/css/font.css";
import "@/assets/less/testPaper.less";
import { quillEditor } from "vue-quill-editor";
import * as Quill from "quill";
import Upload from "@/views/modules/oss/oss-upload.vue";

//quill编辑器的字体
var fonts = [
  "SimSun",
  "SimHei",
  "Microsoft-YaHei",
  "KaiTi",
  "FangSong",
  "Arial",
  "Times-New-Roman",
  "sans-serif",
  "Segoe-UI",
];
var Font = Quill.import("formats/font");
Font.whitelist = fonts; //将字体加入到白名单
Quill.register(Font, true);

// 自定义字号的大小
var sizes = [false, "16px", "18px", "20px", "22px", "26px", "28px", "30px"];
var Size = Quill.import("formats/size");
Size.whitelist = sizes;

const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
  // ["blockquote", "code-block"], // 引用  代码块
  // [{ header: 1 }, { header: 2 }], // 1、2 级标题
  // [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
  [{ script: "sub" }, { script: "super" }], // 上标/下标
  // [{ indent: "-1" }, { indent: "+1" }], // 缩进
  // // [{'direction': 'rtl'}],                         // 文本方向
  [{ size: sizes }], // 字体大小
  // [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  // [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
  [{ font: fonts }], // 字体种类
  // [{ align: [] }], // 对齐方式
  ["clean"], // 清除文本格式
  // ["image"], // 链接、图片、视频
];
export default {
  components: {
    quillEditor,
    Upload,
  },
  data() {
    return {
      values: [],
      excludeId: -1,
      path: "",
      uploadVisible: false,
      isLoading: false,
      editQuestionVisible: false,
      typeId: 3,
      myEditor: {
        dialogVisible: false,
        groupedIndex: -1,
        questionIndex: -1,
        judgeIndex: -2,
        content: "",
      },
      //富文本编辑器配置
      editorOption: {
        placeholder: "",
        theme: "snow", // or 'bubble'
        placeholder: "请输入内容",
        modules: {
          toolbar: {
            container: toolbarOptions,
            // container: "#toolbar",
            handlers: {
              // image: function (value) {
              //   if (value) {
              //     // 触发input框选择图片文件
              //     this.$http({
              //       url: this.$http.adornUrl("/exam/exam/upload/picture"),
              //       method: "post",
              //       data: this.$http.adornData({
              //         "file": value
              //       })
              //     }).then(({ data }) => {
              //       if (data && data.code === 0) {
              //         this.$message.success(data.msg);
              //       } else {
              //         this.$message.error(data.msg);
              //       }
              //     });
              //   } else {
              //     this.quill.format("image", false);
              //   }
              // },
            },
          },
        },
      },
      examData: {
        id: "",
        examTitle: "点击编辑试卷名称",
        categoryId: "",
        type: 3,
        limitTime: 60,
        questions: [
          {
            id: null,
            analysis: "1",
            questionTopic: "点击编辑问题",
            answer: "点击编辑答案",
            typeId: null,
            examId: null,
          },
          {
            id: null,
            analysis: "2",
            questionTopic: "点击编辑问题",
            answer: "点击编辑答案",
            typeId: null,
            examId: null,
          },
        ],
      },
      //试卷分类
      examOptions: [],
      //试题分类
      questionOptions: [],
      //当前question标签
      currQuestion: "1",
      //当前question下标
      questionIndex: 2,
    };
  },
  created() {
    this.getExamOptions();
    this.getQuestionTypeOptions();
  },
  mounted() {
    //  自定义粘贴图片功能
    let quill = this.$refs.myQuillEditor.quill;
    this.$forceUpdate();
    quill.root.addEventListener(
      "paste",
      (evt) => {
        if (
          evt.clipboardData &&
          evt.clipboardData.files &&
          evt.clipboardData.files.length
        ) {
          evt.preventDefault();
          [].forEach.call(evt.clipboardData.files, (file) => {
            if (!file.type.match(/^image\/(gif|jpe?g|a?png|bmp)/i)) {
              return;
            }
            const formData = new FormData();
            formData.append("file", file);
            this.$http({
              url: this.$http.adornUrl(`/exam/exam/upload/picture`),
              method: "post",
              data: formData,
            }).then(({ data }) => {
              if (data && data.code === 0) {
                let length = quill.getSelection().index; //光标位置
                // 插入图片  图片地址
                quill.insertEmbed(length, "image", data.url);
                // 调整光标到最后
                quill.setSelection(length + 1); //光标后移一位
              } else {
                this.$message.error(data.msg);
              }
            });
          });
        }
      },
      false
    );
  },
  methods: {
    save() {
      const examTitle = this.examData.examTitle;
      const limitTime = this.examData.limitTime;
      const categoryId = this.examData.categoryId;
      if (!examTitle) {
        this.$message.error("试卷标题不能为空!");
        return;
      }
      if (!limitTime) {
        this.$message.error("考试时限不能为空!");
        return;
      }
      if (!categoryId) {
        this.$message.error("请选择试卷分类!");
        return;
      }
      const validate = this.validateData();
      if (!validate) {
        this.editQuestionVisible = true;
        return;
      }
      this.isLoading = true;
      this.$http({
        url: this.$http.adornUrl(`/exam/exam/update/interview`),
        method: "post",
        data: this.$http.adornData(this.examData),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            type: "success",
            message: data.msg,
          });
          Object.assign(this.$data.examData, this.$options.data().examData);
          this.questionIndex = this.examData.questions.length;
          this.currQuestion = this.questionIndex + "";
          this.$parent.changeState();
          this.$router.push({
            name: `exam-list`,
          });
        } else {
        }
        this.isLoading = false;
      });
    },
    //校验数据
    validateData() {
      let list = [];
      for (let i = 0; i < this.examData.questions.length; i++) {
        const typeId = this.examData.questions[i].typeId;
        if (!typeId) {
          this.$message.error(
            "请选择" + this.getQuestionPrefix(i) + "对应的分类"
          );
          return false;
        }
      }
      return true;
    },
    init(examData) {
      if (examData) {
        console.log(examData);
        this.examData = examData;
        this.questionIndex = this.examData.questions.length;
        this.currQuestion = this.questionIndex + "";
      }
      let id = this.examData.categoryId;
      this.$http({
        url: this.$http.adornUrl(`/exam/examcategory/path/${id}`),
        method: "post",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.path = data.path;
        } else {
          this.path = [];
        }
      });
    },
    //上传申论试卷事件
    uploadInterView() {
      this.uploadVisible = true;
      this.$nextTick(() => {
        this.$refs.upload.init("/exam/exam/upload/interview");
      });
    },
    //确认修改题目数据
    questionEditConfirm() {
      const vaildate = this.validateData();
      if (vaildate) {
        this.$message.success("编辑成功!");
        this.editQuestionVisible = false;
      }
    },
    //获取申论试卷数据
    getExamData(examData) {
      if (examData.type) {
        this.examData = examData;
        this.questionIndex = this.examData.questions.length;
        this.currQuestion = this.questionIndex + "";
      }
    },
    //获取试卷分类选项
    getExamOptions() {
      this.$http({
        url: this.$http.adornUrl(`/exam/examcategory/tree`),
        method: "post",
        data: this.excludeId,
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.examOptions = data.data;
        } else {
          this.examOptions = [];
        }
      });
    },
    //获取题目分类选项
    getQuestionTypeOptions() {
      this.$http({
        url: this.$http.adornUrl(`/question/questiontype/tree/${this.typeId}`),
        method: "post",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.questionOptions = data.questionTypeOptions;
        } else {
          this.questionOptions = [];
        }
      });
    },
    //试卷分类变化事件
    examCategorychange(value) {
      let id = value[value.length - 1];
      this.examData.categoryId = id;
    },
    questionTypeOptionChange(value, index) {
      let id = value[value.length - 1];
      this.examData.questions[index].typeId = id;
    },
    inputClick(index, content, judgeIndex) {
      this.myEditor.index = index;
      this.myEditor.content = content;
      this.myEditor.judgeIndex = judgeIndex;
      this.myEditor.dialogVisible = true;
    },
    editorConfirm() {
      this.myEditor.dialogVisible = false;
      let index = this.myEditor.index;
      let content = this.myEditor.content;
      let judgeIndex = this.myEditor.judgeIndex;
      if (!content) {
        return;
      }
      if (judgeIndex == 0) {
        this.examData.questions[index].answer = content;
      } else if (judgeIndex == 1) {
        this.examData.questions[index].questionTopic = content;
      }
    },
    getQuestionPrefix(index) {
      this.examData.questions[index].sort = index + 1;
      return "问题" + (index + 1);
    },
    getAnswerPrefix(index) {
      this.examData.questions[index].sort = index + 1;
      return "答案" + (index + 1);
    },
    addQuestion(targetName) {
      let newTabName = ++this.questionIndex + "";
      this.examData.questions.push({
        id: null,
        analysis: newTabName,
        questionTopic: "点击编辑问题",
        answer: "点击编辑答案",
        typeId: null,
        examId: null,
      });
      this.currQuestion = newTabName;
    },
    removeQuestion(targetName) {
      let tabs = this.examData.questions;
      let activeName = this.currQuestion;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.analysis === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.analysis;
            }
          }
        });
      }
      this.currQuestion = activeName;
      this.examData.questions = tabs.filter(
        (tab) => tab.analysis !== targetName
      );
    },
  },
};
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
}

.el-tab-pane {
  height: 200px;
  overflow: auto;
  cursor: pointer;
}
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-thumb {
  background: rgba(20, 20, 20, 0.2);
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background: transparent;
}
</style>